package main

import (
	"context"
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"github.com/docker/docker/api/types"
	"github.com/docker/docker/client"
	"io/ioutil"
	"net/http"
	"os"
	"time"
)

type (
	Endpoint struct {
		URL           string
		TLSConfig     TLSConfiguration
		TLS           bool
		TLSCACertPath string
		TLSCertPath   string
		TLSKeyPath    string
	}
	TLSConfiguration struct {
		TLS           bool
		TLSSkipVerify bool
		TLSCACertPath string
		TLSCertPath   string
		TLSKeyPath    string
	}
)

func main() {
	root, _ := os.Getwd()
	fmt.Print(root)
	endpoint:= &Endpoint{}
	ctx := context.Background()
	endpoint.URL = "http://39.96.24.186:2376"
	endpoint.TLS=true
	endpoint.TLSConfig.TLS=true
	endpoint.TLSCACertPath = root + "/.docker/ca.pem"
	endpoint.TLSConfig.TLSCACertPath = root + "/.docker/ca.pem"
	endpoint.TLSCertPath = root + "/.docker/cert.pem"
	endpoint.TLSConfig.TLSCertPath = root + "/.docker/cert.pem"
	endpoint.TLSKeyPath =  root + "/.docker/key.pem"
	endpoint.TLSConfig.TLSKeyPath =  root + "/.docker/key.pem"
	cli, err := createTCPClient(endpoint)
	if err != nil {
		panic(err)
	}

	images, err := cli.ImageList(ctx, types.ImageListOptions{})
	if err != nil {
		panic(err)
	}

	for _, image := range images {
		fmt.Println("\n"+image.ID+"\n")
		fmt.Println(image.Created)
		fmt.Println("\n")
		fmt.Println(image.Labels)
		fmt.Println("\n")
		fmt.Println(image.Size)
	}
}
func createTCPClient(endpoint *Endpoint) (*client.Client, error) {
	httpCli, err := httpClient(endpoint)
	if err != nil {
		return nil, err
	}

	return client.NewClientWithOpts(
		client.WithHost(endpoint.URL),
		client.WithVersion("1.37"),
		client.WithHTTPClient(httpCli),
	)
}

func CreateTLSConfigurationFromDisk(caCertPath, certPath, keyPath string, skipServerVerification bool) (*tls.Config, error) {
	config := &tls.Config{}
	config.InsecureSkipVerify = skipServerVerification

	if certPath != "" && keyPath != "" {
		cert, err := tls.LoadX509KeyPair(certPath, keyPath)
		if err != nil {
			return nil, err
		}

		config.Certificates = []tls.Certificate{cert}
	}

	if !skipServerVerification && caCertPath != "" {
		caCert, err := ioutil.ReadFile(caCertPath)
		if err != nil {
			return nil, err
		}

		caCertPool := x509.NewCertPool()
		caCertPool.AppendCertsFromPEM(caCert)
		config.RootCAs = caCertPool
	}

	return config, nil
}
func httpClient(endpoint *Endpoint) (*http.Client, error) {
	transport := &http.Transport{}
	if endpoint.TLSConfig.TLS {
		tlsConfig, err := CreateTLSConfigurationFromDisk(endpoint.TLSConfig.TLSCACertPath, endpoint.TLSConfig.TLSCertPath, endpoint.TLSConfig.TLSKeyPath, endpoint.TLSConfig.TLSSkipVerify)
		if err != nil {
			return nil, err
		}
		transport.TLSClientConfig = tlsConfig
	}

	return &http.Client{
		Transport: transport,
		Timeout:   10 * time.Second,
	}, nil
}
